import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {ResultJson} from '../entity/result-json';
import {SettingsService} from '../settings/settings.service';
import { catchError, map, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
declare var $: any;
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json'})
};
@Injectable()
export class BaseService {
  private baseUrl: string;
  constructor(private http: HttpClient, private setting: SettingsService) {
    this.baseUrl = this.setting.getBaseServerUrl();
  }

  get (options: {
    url: string,
    params?: {}
  }): Observable<ResultJson> {
    if (options.params) {
      httpOptions['params'] = options.params;
    }
    console.log('sssss', httpOptions['params']);
    return this.http.get<ResultJson>(this.baseUrl + options.url, httpOptions).pipe(
      tap((rj: ResultJson) => this.log(`${rj.msg}`)),
      catchError(this.handleError<ResultJson>('get'))
    );
  }

  post (options: {
    url: string,
    params?: {}
  }): Observable<ResultJson> {
    return this.http.post<ResultJson>(this.baseUrl + options.url, options.params, httpOptions).pipe(
      tap((rj: ResultJson) => this.log(`${rj.msg}`)),
      catchError(this.handleError<ResultJson>('post'))
    );
  }

  put (options: {
    url: string,
    params?: {}
  }): Observable<ResultJson> {
    return this.http.put<ResultJson>(this.baseUrl + options.url, options.params).pipe(
      tap((rj: ResultJson) => this.log(`${rj.msg}`)),
      catchError(this.handleError<ResultJson>('put')));
  }

  /**
   * Handle Http operation that failed.
   * Let the app continue.
   * @param operation - name of the operation that failed
   * @param result - optional value to return as the observable result
   */
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      this.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

  private log(msg: String) {
    console.log(msg);
  }
}
